0

異なるリストビューとオプションを持つ簡単なタブ付きアプリケーションを作成しようとしています。 タブとMainActivityとの関係を管理したいと思っています。現在、メニューボタンにaddItem()関数を作成して、タブ付きアプリケーションのListView(フラグメント内)に新しいアイテムを追加することはできません。 私はすでにたくさんの検索を行っていますが、単純なListView(MainActivity内)に項目を追加するか、タブ付きアプリケーションで項目を動的に追加することができませんでした。アンドロイド - フラグメントリスト(タブ付き)に新しいアイテムを追加する - Android Studio

ここでは、私が作業しようとしている私のタブ付きアプリケーションとリストビューの画面です。 Custom List View Application Picture

[1]: https://i.stack.imgur.com/Ze4eu.png

そして、ここに私のコードです: 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との断片は、I)は、(メニューボタン方式の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(); 
    } 

} 

My 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; 
    } 
} 
+0

申し訳ありませんが、私はそれを取得しませんでした。あなたは、メニュー項目をクリックし、その更新のリストを表示できるようにその追加のリストを通知することによって項目をリストに追加したいですか? –

+0

そうですね、メニュー項目でリストに項目を追加してください。 問題は.. MainActivityのリストとメニュー項目を実装しますが、フラグメントに実装することはできません。 したがって、2つのオプションがあります。まず、MainActivityのCustomListとすべてのメニューボタンを実装しますが、この "made Custom List"をフラグメント( "catalogo"タブ)に渡す方法はわかりません。 もう一つは、フラグメント( "Catalogo"タブ)内のすべてを実装していますが、MainActivityのようなボタン機能を実装できません。 –

+0

これは知っているだけです。カタログの断片が表示されているとき、またはいつもそれを見るときに「追加」ボタンが表示されますか? –

答えて

0

フラグメントの活動のデータを使用するための最良の方法は、

アクティビティクラスに
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); 
    } 
    } 

をフラグメントのインターフェイスを作成して実装することで、アクティビティクラスでこのインターフェイスを実装する

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

このように、すべてのデータとリストビューは同じクラスに存在します。 これが今あなたを助けてくれることを願っています。

+0

私は私の答えを編集しました –

+0

ああ申し訳ありませんが、私はこの答えをここに書きました。変数名を変更することができます –

+0

あなたと私のコードを混ぜるときにうんざりしました。ご不便おかけしてすみません。 –

0

まず最初に、あなたの商品を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);

などの項目を取得することにより、ここにすべてのlistnersと低いものを実装することができますお手伝いをする可能性のあるインフォメーションチェックthis answer(他にもたくさんあります)

は、今、私たちは欠場何リストビューをリフレッシュされ、これは私が考える最も簡単な方法です:

あなたのActivityにカスタムFragmentの参照を保存することができます。次に、FragmentAddItemToList()のようなメソッドを追加します。今、ユーザーがボタンを "追加"、あなたはフラグメント参照からこのメソッドを呼び出すと、以下のような方法を実装することができますクリックする(+ - ):

コールバック(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(); 
} 

何かが私がここにいる任意の質問や、について説明するために...動作するはずです。幸運

+0

フラグメント内でコールバックを 'onAttach' ? –

関連する問題