Как я могу использовать Android фрагмент Java-класс?

java android android-fragments

924 просмотра

2 ответа

Я установил фрагмент, который выглядит так:

EditText ("5") имеет идентификатор et_input. Теперь я хочу взаимодействовать с моим EditText, но он не работает.

MainActivity.java

public class MainActivity extends AppCompatActivity {

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a
 * {@link FragmentPagerAdapter} derivative, which will keep every
 * loaded fragment in memory. If this becomes too memory intensive, it
 * may be best to switch to a
 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
private SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
private ViewPager mViewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);

    getSupportActionBar().hide();
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    public PlaceholderFragment() {
    }

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        switch (getArguments().getInt(ARG_SECTION_NUMBER) - 1) {
            case 1:
                return inflater.inflate(R.layout.fragment_roman_numbers, container, false);
            case 2:
                return inflater.inflate(R.layout.fragment_binary_numbers, container, false);
            default:
                return inflater.inflate(R.layout.fragment_main, container, false);
        }
    }
}

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        if(position == 0) {
            return main.newInstance();
        } else if(position == 1) {
            return roman_numbers.newInstance();
        } else if(position == 2) {
            return binary_numbers.newInstance();
        }
        throw new IllegalArgumentException("There is no fragment for position [" + position + "]");
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 3;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return getString(R.string.fragment_home);
            case 1:
                return getString(R.string.fragment_roman_numbers);
            case 2:
                return getString(R.string.fragment_binary_numbers);
        }
        return null;
    }
}
}

binary_numbers.java

public class binary_numbers extends Fragment {

public binary_numbers() {
    // Required empty public constructor
}

public static binary_numbers newInstance() {
    binary_numbers fragment = new binary_numbers();
    return fragment;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_binary_numbers, container, false);
    EditText et_input = (EditText) view.findViewById(R.id.et_input);
    et_input.setText("TEST");

    // Inflate the layout for this fragment
    return view;
}
}

roman_numbers.java и main.java выглядят одинаково, за исключением того, что имена двоичных_изменений заменяются их именами.

fragement_binary_numbers.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.ngtnttnmnt.xtool.MainActivity$PlaceholderFragment">


<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="number"
    android:ems="10"
    android:id="@+id/et_input"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="100dp"
    android:hint="@string/input_hint"
    android:gravity="center" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text=""
    android:id="@+id/tv_output"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:textSize="40dp"
    android:gravity="center" />

fragement_roman_numbers.xml выглядит точно так же, а fragement_main.xml имеет два TextView

Автор: creativecreatorormaybenot Источник Размещён: 08.11.2019 11:19

Ответы (2)


1 плюс

Решение

Должно быть

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_binary_numbers, container, false);
    EditText et_input = (EditText) view.findViewById(R.id.et_input);
    et_input.setText("TEST");

    // Inflate the layout for this fragment
    return view;
}

РЕДАКТИРОВАТЬ:

Как я уже сказал, вы показываете другой фрагмент. В действительности вы показываете PlaceholderFragmentсозданное внутри себя SectionsPagerAdapter, которое просто выбирает binary_numberмакет, когда он раздут, но на самом деле вы не показываете binary_numbersфрагмент.

Ваш код должен быть следующим:

public class MainActivity extends AppCompatActivity {

private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);

    getSupportActionBar().hide();
}

public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        if(position == 0) {
            return home.newInstance();
        } else if(position == 1) {
            return roman_numbers.newInstance();
        } else if(position == 2) {
            return binary_numbers.newInstance();
        }
        throw new IllegalArgumentException("There is no fragment for position [" + position + "]");
    }

    @Override
    public int getCount() {
        return 3;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return getString(R.string.fragment_home);
            case 1:
                return getString(R.string.fragment_roman_numbers);
            case 2:
                return getString(R.string.fragment_binary_numbers);
        }
        throw new IllegalArgumentException("There is no fragment for position [" + position + "]");
    }
}
}

Обратите внимание на полное удаление PlaceholderFragmentкласса, потому что оно вам никогда не понадобится.

РЕДАКТИРОВАТЬ: также добавить

public class home extends Fragment {
    public static home newInstance() {
        return new home();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState) {
         return inflater.inflate(R.layout.fragment_main, container, false);
    }
}

РЕДАКТИРОВАТЬ:

Также измените свой binary_numbersкласс так

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.InputFilter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import com.ngtnttnmnt.xtool.InputFilterMinMax;
import com.ngtnttnmnt.xtool.R;

public class binary_numbers extends Fragment {

public binary_numbers() {
    // Required empty public constructor
}

public static binary_numbers newInstance() {
    binary_numbers fragment = new binary_numbers();
    return fragment;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_binary_numbers, container, false);
    EditText et_input = (EditText) view.findViewById(R.id.et_input);
    et_input.setText("TEST");

    // Inflate the layout for this fragment
    return view;
}
}
Автор: EpicPandaForce Размещён: 20.08.2016 12:38

-1 плюса

public class SectionsPagerAdapter extends FragmentPagerAdapter {
private PlaceholderFragment mPlaceholderFragment;
public SectionsPagerAdapter(FragmentManager fm) {
    super(fm);
}

@Override
public Fragment getItem(int position) {
    if(mPlaceholderFragment == null){
      mPlaceholderFragment = PlaceholderFragment.newInstance(position + 1);
    }
    return mPlaceholderFragment;
}

Так должно быть

Автор: Karacago Размещён: 20.08.2016 01:31
Вопросы из категории :
32x32