2017-09-01 10 views
0

私の質問はthisと重複しているようですが、同じ方法を別の方法で取り組んでいます。共有設定を使用してボタンを動的に作成し、ボタンに関連付けられたデータにアクセスするためにonClickListenerを設定する

私は断片で働いているし、この特定のシナリオでは、私は2つの断片、フラグメントフラグメントBを持っています。

フラグメントAはフラグメントBの外部DBへの呼び出しが行われに、フラグメントB呼び出し、データ共有プリファレンスに保存されています。このデータは、再度断片に渡される

、ループは、その後shared preferencesに記憶されたIDのうちどのがループを作り、リニアレイアウトに追加されたボタンに追加されます。

これはすべて問題なく動作しますが、各ボタンにOnClickListenersを追加したいと思います。各ボタンには異なる機能があります(基本的に、各ボタンは自分のDBに格納された個々の質問を表し、アクセスします)。ここで

は、動的なボタンが作成された私の方法です:

@TargetApi(Build.VERSION_CODES.M) 
public void createQuestionButton() { 

    //get all the question_ids from shared pref, that have been stored from the SetQuestion Activity 
    //in the allQuestionIDS() method 
    String questionNumber = pref.getString(Constants.All_QUESTION_IDS, ""); 


    //converting the above String back into a List 
    questionNumber = questionNumber.substring(1, questionNumber.length() - 1); 
    //split the array using the comma 
    String[] array = questionNumber.split(","); 
    //Converting questionArray array to a list using Arrays.asList() 
    List list = Arrays.asList(array); 


    if (!questionNumber.equals("") && !questionNumber.equals(null)) { 

     for (final Object value : list) { 

      try { 

     /*Dynamically create new Button which includes the question number 
      */ 

       btn_question = new AppCompatButton(getActivity()); 

     /*LayoutParams (int width, int height,float weight) 
     As LayoutParams is defaulted in px, I have called a method called dpToPX to make sure 
     the dynamically added Button is the same size on all devices. 
     */ 
       LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(dpToPx(280), dpToPx(45), 1); 
       btn_question.setBackgroundColor(Color.parseColor("#3B5998")); 
       btn_question.setTextColor(Color.WHITE); 
       btn_question.setText("Question " + value); 
       btn_question.setGravity(Gravity.CENTER); 
       //generate unique ID for each new Button dynamically created 
       btn_question.setId(View.generateViewId()); 
       params.setMargins(0, dpToPx(10), 0, dpToPx(10)); 
       btn_question.setPadding(0, 0, 0, 0); 
       btn_question.setLayoutParams(params); 
       //allEds.add(btn_question); 
       btn_question.setTag(btn_question); 

       btn_question.setOnClickListener(this); 
       mLayout.addView(btn_question); 



       //Toast.makeText(getActivity(), "Question ID = " + btn_question.getId(), 
         // Toast.LENGTH_LONG).show(); 

      } catch (Exception e) { 
       Log.d(TAG, "Failed to create new button"); 
      } 
     } 


    } 

} 

その後、私はここに

@Override 
public void onClick(View view) { 


    switch (view.getId()) 
    { 

     case R.id.btn_add_question: 
      goToQuestion(); 

      break; 

     case R.id.btn_remove_all_questions: 
      //show dialog box asking if user definitely wants to remove all questions 
      showDialog(); 
      break; 


     // case btn_question.getId(): 
    } 

} 

XML

<?xml version="1.0" encoding="utf-8"?> 

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" 
android:id="@+id/mScrollView" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:fillViewport="true"> 

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
     xmlns:tools="http://schemas.android.com/tools" 
     android:id="@+id/create_questions" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:background="@color/facebookBlue" 
     android:orientation="vertical" 
     android:weightSum="1"> 


    <android.support.design.widget.TextInputEditText 
     android:id="@+id/tv_setQuestions" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_gravity="center_horizontal" 
     android:inputType="none" 
     android:text="@string/setQuestions" 
     android:textColor="@android:color/background_light" 
     android:textColorLink="@android:color/background_light" 
     android:textSize="30sp" 
     android:textStyle="bold" /> 


    <FrameLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:weightSum="1"> 

     <TextView 
      android:id="@+id/textView3" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:layout_gravity="center" 
      android:gravity="center" 
      android:text="Press 'Add Question' to Add a Question and it's Answer" 
      android:textColor="@android:color/background_light" 
      android:textSize="24sp" /> 

    </FrameLayout> 


    <LinearLayout 
     android:id="@+id/buttonGroupLayout" <-----Here is where the dynamic button is added 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_gravity="center" 
     android:gravity="center" 
     android:orientation="vertical"> 

    </LinearLayout> 

    <FrameLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:weightSum="1"> 

     <android.support.v7.widget.AppCompatButton 
      android:id="@+id/btn_add_question" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:layout_marginLeft="40dp" 
      android:layout_marginRight="40dp" 
      android:layout_marginTop="8dp" 
      android:background="@color/colorPrimary" 
      android:text="Add Question" 
      android:textColor="@android:color/white" /> 

    </FrameLayout> 

    <FrameLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:weightSum="1"> 

     <android.support.v7.widget.AppCompatButton 
      android:id="@+id/btn_remove_all_questions" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:layout_marginLeft="40dp" 
      android:layout_marginRight="40dp" 
      android:background="@color/colorPrimary" 
      android:text="@string/removeAllQuestions" 
      android:textColor="@android:color/white" /> 

    </FrameLayout> 


    <ProgressBar 
     android:id="@+id/progress" 
     style="@style/Base.Widget.AppCompat.ProgressBar" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentStart="true" 
     android:layout_below="@+id/btn_submit_team" 
     android:layout_marginTop="26dp" 
     android:indeterminate="true" 
     android:visibility="invisible" /> 


</LinearLayout> 

を各ボタンを呼び出すようにしようとしていますまず、私はgenerateViewId()を使用する必要がある各ボタンにアクセスすると考えられますが、IDはXML内のボタンの位置に依存します。

代わりにsetTagが必要であることを読んでいますが、今は実装方法を混乱させ、onClick内の個々のボタンでアクセスしています。

本当にありがとうございます。

+0

あなたのソリューションは実現可能なようですが、私はちょっと長いでしょう:フラグメントBからAへデータを送信するときは、あなたのアクティビティを使ってそれを行うのがプロフェッショナルです。その後、ボタンデータのリストを取得すると、ループを介してそれぞれのデータが膨張します。また、ループ中は、そのボタンのDBから各ボタンにIDでOnclickListenerを設定します。次に、クリックコマンドで受け取る別の方法では、あなたのボタンでidからdbのidを取得すると、そのIDですべてのデータが必要になります –

+0

@SA以下の方法をチェックできますか? – phpdroid

答えて

0

最後に、私はsetTagについてさらに研究を行い、これが行く方法だと決めました。

私の拡張forループの一部として、btn_question.setTag(value);が含まれています。これは、要素がXML上のどこにあっても一意のタグを作成するためです。

次に、拡張ループ内にもう一度btn_question.setOnClickListener(this);を追加し、次にクリックした相対ボタンを呼び出しました。

@Override 
public void onClick(View view) { 

    view.getTag();{ 
     Toast.makeText(getActivity(), "Question ID = " + view.getTag(), 
       Toast.LENGTH_LONG).show(); 

    } 

トーストは、選択した値が正しいことを確認します。

0

私の方法がどれほどうまくいくか分かりませんが、私のプロジェクトでこの方法を使用しています。
だから私は動的にここに

int buttona=10*idz+1; 
    int buttonab=10*idz+2; 
    int buttonac=10*idz+3; 
    int buttonad=10*idz+4; 
    int buttonae=10*idz+5; 
    int buttonaf=10*idz+6; 

idzとしての私のボタンのIDを作成するには、データベースから一意のID(例:ユーザーID)することができ、あなたは毎回ループスルーして、新しいidを傷薬とそれぞれのボタンに何
それらを設定することができます私のXMLでやっていることはクリックで関数を呼び出すです: - ここ

<ImageButton android:background="@drawable/share" 
     android:layout_height="36dp" 
     android:layout_width="36dp" 
     android:padding="10dp" 
     android:onClick="click" 
     android:layout_marginTop="10dp" 
     android:id="@+id/button_share" 
     /> 


click関数を呼び出していますし、click機能に私はすべての要求を処理することができますボタンのようにクリックされます: -

public void click(View view) { 

    Context context = getApplicationContext(); 
    final int position = view.getId(); 
    int button_number = position % 10; 
    int id = position/10; 
    // now I can know which button is click through button_number can do respectively through if loop 
    // what i have to do to data using id 
+0

このアプローチではなく、私が言及していないビット)))あなたがボタンのIDを作成するときにIDはdbになることができます。上記で作成したids uがdbに存在しない可能性があります。そのため、「そのようなIDエラーはありません」という結果になる可能性があります。だから、私たちが持っているものを入手する方が良いと思われます) –

+0

@SAここで 'idz'パラメータはdbに存在する適切なIDを作成するためにデータベース自体から取得されます – phpdroid

+0

あなたのID間にあるので、結果は1,2,3 .. 6から1,3 ... 6に変わります。結果はあなたのケースで考慮されるべきではありません。) –

関連する問題