【问题标题】:ANDROID - Add new Items in a Fragment List (Tabbed) - Android StudioANDROID - 在片段列表中添加新项目(选项卡式) - Android Studio
【发布时间】:2017-09-05 12:51:07
【问题描述】:

我正在尝试使用不同的 ListViews 和选项制作一个简单的选项卡式应用程序。 我想管理选项卡和 MainActivity 之间的关系,现在的问题是我无法在菜单按钮中创建 addItem() 函数,以便在选项卡式应用程序中向我的 ListView(在 Fragment 内)添加新项目。 我已经搜索了很多,但我发现只在一个简单的 ListView(在 MainActivity 内)中添加一个项目或在选项卡式应用程序中添加非动态项目。

所以这里是我的选项卡式应用程序的屏幕和我正在尝试使用的 ListView。 Custom List View Application Picture

这是我的代码: MainActivity.java

public class MainActivity extends AppCompatActivity {



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);

}

带有CustomList的片段,我正在尝试实现菜单按钮方法action_add():

    public class Catalogo extends Fragment {
    ArrayList<CustomList> custom = null;
    ListView lv = null;
    ArrayAdapter adapter = null;
    ArrayList<CustomList> elementos = new ArrayList<CustomList>();

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.catalogo, container, false);
        ListView lv = rootView.findViewById(R.id.catalogoListView);

        custom = addItems();
        adapter = new CustomAdapter(this.getContext(), custom);
        lv.setAdapter(adapter);

        return rootView;
    }

    private ArrayList<CustomList> addItems(){
        CustomList custom = new CustomList("Banana", "4.0");
        elementos.add(custom);
        custom = new CustomList("Morango", "5.0");
        elementos.add(custom);
        return elementos;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();


        if (id == R.id.action_add){
            AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
            //builder.setTitle("Adicionar novo item"); //THESE ARE NOT WORKING
            //final EditText input = new EditText(this); //THIS SHOULD BE 2 Text Fields
            //builder.setView(input);
            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //NEED TO IMPLEMENT HERE
                }
            });
            builder.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
            builder.show();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
    public static String preferredCase(String original, String price)
    {
        if (original.isEmpty())
            return original;

        return original.substring(0, 1).toUpperCase() + original.substring(1).toLowerCase();
    }

}

我的 CustomItem 结构:

   public class CustomList {
    String name;
    String price;
    public CustomList(String name, String price) {
        this.name = name;
        this.price = price;
    }
    public String getName() {
        return name;
    }
    public String getPrice() {
        return price;
    }
}

最后,我的 CustomAdapter:

    public class CustomAdapter extends ArrayAdapter<CustomList> {
    private final Context context;
    private final ArrayList<CustomList> elementos;

    public CustomAdapter(Context context, ArrayList<CustomList> elementos){
        super(context, R.layout.modelolista, elementos);
        this.context = context;
        this.elementos = elementos;
    }
    public View getView(int position, View convertView, ViewGroup parent){
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View rowView = inflater.inflate(R.layout.modelolista, parent, false);

        TextView nameItem =  rowView.findViewById(R.id.tvName);
        TextView priceItem =  rowView.findViewById(R.id.tvPrice);

        nameItem.setText(elementos.get(position).getName());
        priceItem.setText(elementos.get(position).getPrice());

        return rowView;
    }
}

【问题讨论】:

  • 抱歉,我没听懂。您想通过单击菜单项并通知添加的列表来将项目添加到列表中,以便它可以显示更新后的列表?
  • 是的,你是对的,在菜单项的列表中添加一个项目。问题是……我在 MainActivity 中实现了列表和菜单项……但我无法在 Fragment 中实现它们。所以,有两个选项。首先,在 MainActivity 中实现 CustomList 和所有菜单按钮,但是我不知道如何将这个“制作的自定义列表”传递给片段(在“目录”选项卡中)。其次,在 Fragment(“Catalogo”选项卡)中实现所有内容,但是,我无法像在 MainActivity 中那样实现按钮功能。
  • 好的,只是想知道:只有在显示目录片段时才会看到“添加”按钮,或者您总是看到它?
  • 总是这样,我在 MenuLayout 中制作了添加按钮。但是很抱歉,看起来如此混乱,所以我将重新制作所有内容并再次发布。

标签: java android listview android-fragments android-tablayout


【解决方案1】:

首先建议:不要将您的项目称为CustomList,而应考虑将其称为CustomListItem。这样您以后会很容易记住它是一个项目,而不是一个列表。

也就是说,您应该实现一个添加页面\对话框。

有很多方法可以做到这一点..“最佳方法”(我认为)将创建一个自定义添加对话框。因此,您必须创建一个自定义布局并将其作为您的布局视图,如下所示:

AlertDialog.Builder builder = new AlertDialog.Builder(activity);
LayoutInflater inflater = activity.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.my_custom_view, null);
builder.setView(dialogView);

现在您可以通过将项目获取为Button byButton = (Button)dialogView.getItemById(R.id.mybutton); 来简单地在此处实现所有侦听器和东西

有关任何可能对您有帮助的信息,请查看this answer(还有很多其他信息)。

现在我们错过的是刷新列表视图,我认为这是最简单的方法:

您可以将自定义Fragment 的引用保存在您的Activity 中。然后在您的Fragment 中添加类似AddItemToList() 的方法。现在,当用户单击“添加”按钮时,您可以从片段引用中调用此方法并实现以下方法(+-):

回调(MainActivity)

//add this param
private MyFragment myFragment;

//when you show the fragment add this:
myFragment = myFragmentIstance;

//on the save of the dialog, add this:
//do all checks and create item
CustomListItem cli = new CustomListItem(editTextName.getText().toString(), editTextPrice.getText().toString());
myFragment.AddItemToList(cli);

AddItemToList(片段):

public void AddItemToList(CustomListItem cli){
  myCustomListItemList.Add(cli);
  myAdapterView.notifyDataSetChanged();
}

这样的事情应该可以工作。对于任何问题或解释,我都在这里。祝你好运

【讨论】:

  • Fragment中的回调不应该是onAttach吗?
【解决方案2】:

在fragment中使用activity的数据最好的方式是在fragment中创建一个接口并在activity类中实现

    public class Catalogo extends Fragment {
    private CatalogFragmentInteface catalogInterface;
    //rest of your code

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.catalogo, container, false);
            catalogIntreface.catalogInterfaceFunction(rootView);
    }
@Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof CatalogFragmentInterface) {
            catalogInterface = (CatalogFragmentInterface) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement CatalogFragmentInterface");
        }
    }

    interface CatalogFragmentInterface {
        void catalogInterfaceFunction(View view);
    }
    }

在你的 Activity 类中实现这个接口

public class MainActivity extends AppCompatActivity implement Catalog.CatalogFragmentInterface{
@Overide
void catalogInterfaceFunction(View view) {
    //access your listview in fragment using view variable
}
}

通过这种方式,您的所有数据和列表视图都存在于同一个类中。 我希望这对你现在有帮助。

【讨论】:

  • 对不起,我没有注意到,我在这里写了这个答案。您可以更改变量名称
  • 是的,我在混合你和我的代码时搞砸了,现在它从我这边完成了。很抱歉给您带来不便。
  • 现在担心了。您可能想在调用接口方法之前检查 Fragment 是否实际附加
  • 如果你不实现接口,那么在onAttach()执行时会自动抛出错误
猜你喜欢
  • 1970-01-01
  • 2015-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-22
  • 1970-01-01
相关资源
最近更新 更多