2014-02-25 1 views
0

Так что я пытаюсь забрать Java и особенно Android-программирование. Но я довольно новичок в этом, поэтому, пожалуйста, проявляйте терпение :-) Это, наверное, очень просто для вас, экспертов Android и Java.Android создать кнопку внутри фрагмента из-за активности

То, что я хочу выполнить, - это перебрать всех моих друзей и создать кнопку для каждого из них. Работа цикла выполняется, создание кнопки не происходит. Вы можете видеть в коде, что я уже пробовал. В примере на facebook используются две операции: MainActivity, PickerActivity и два фрагмента: SplashFragment, SelectFragment. У меня есть макет для каждой операции и каждого фрагмента. Я хочу разместить кнопку на макете selection.xml, но я не уверен, как это сделать. Надеюсь, я дал понять :-)

Что я делаю, использую facebook sdk и пример Scrumptious Я пытаюсь улучшить friendpicker. Пример и особенно friendpicker уже работает. Он показывает все мои друзья, я могу выбрать их и после нажатия хорошо я могу получить их с помощью friendPickerFragment.getSelection();

код из PickerActivity.java:

friendPickerFragment.setOnDoneButtonClickedListener(
     new PickerFragment.OnDoneButtonClickedListener() { 
    @Override 
    public void onDoneButtonClicked(PickerFragment<?> fragment) { 

    //here I am getting the selected facebook user 
     List<GraphUser> FriendListToPlay = friendPickerFragment.getSelection(); 

     for (GraphUser User: FriendListToPlay) { 
      Log.i("info",User.getId()+' '+User.getName()); 

      /* create button for every facebook user chosen 
      Button myButton = new Button(PickerActivity.this); 
      myButton.setText(User.getName() + " waiting for game"); 

      LinearLayout ll = (LinearLayout)findViewById(R.id.linear_view); 
      LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); 
      ll.addView(myButton, lp); 
      */ 
     } 

     finishActivity(); 
    } 
}); 

SelectionFragment: общественный класс SelectionFragment расширяет фрагмент {

public static String OwnId = ""; 
public static GraphUser OwnUser = null; 

private static final String TAG = "SelectionFragment"; 

private static final int REAUTH_ACTIVITY_CODE = 100; 

private ProfilePictureView profilePictureView; 
private TextView userNameView; 

private ListView listView; 
private List<BaseListElement> listElements; 

private UiLifecycleHelper uiHelper; 
private Session.StatusCallback callback = new Session.StatusCallback() { 
    @Override 
    public void call(final Session session, final SessionState state, final Exception exception) { 
     onSessionStateChange(session, state, exception); 
    } 
}; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    uiHelper = new UiLifecycleHelper(getActivity(), callback); 
    uiHelper.onCreate(savedInstanceState); 
} 

@Override 
public View onCreateView(LayoutInflater inflater, 
     ViewGroup container, Bundle savedInstanceState) { 
    super.onCreateView(inflater, container, savedInstanceState); 
    View view = inflater.inflate(R.layout.selection, 
      container, false); 

// Find the user's profile picture custom view 
    profilePictureView = (ProfilePictureView) view.findViewById(R.id.selection_profile_pic); 
    profilePictureView.setCropped(true); 

    // Find the user's name view 
    userNameView = (TextView) view.findViewById(R.id.selection_user_name);  

// Find the list view 
    listView = (ListView) view.findViewById(R.id.selection_list); 

    // Set up the list view items, based on a list of 
    // BaseListElement items 
    listElements = new ArrayList<BaseListElement>(); 
    // Add an item for the friend picker 
    listElements.add(new PeopleListElement(0)); 
    // Set the list view adapter 
    listView.setAdapter(new ActionListAdapter(getActivity(), 
         R.id.selection_list, listElements)); 

    // Check for an open session 
    Session session = Session.getActiveSession();  

    if (session != null && session.isOpened()) { 
     // Get the user's data 
     makeMeRequest(session); 
    } 


    return view; 
} 

@Override 
public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 
    if (requestCode == REAUTH_ACTIVITY_CODE) { 
     uiHelper.onActivityResult(requestCode, resultCode, data); 

    } else if (resultCode == Activity.RESULT_OK) { 
     // Do nothing for now 
    } 
} 

private void makeMeRequest(final Session session) { 
    // Make an API call to get user data and define a 
    // new callback to handle the response. 
    Request request = Request.newMeRequest(session, new Request.GraphUserCallback() { 
     @Override 
     public void onCompleted(GraphUser user, Response response) { 
      // If the response is successful 
      if (session == Session.getActiveSession()) { 
       if (user != null) { 
        // Set the id for the ProfilePictureView 
        // view that in turn displays the profile picture. 
        profilePictureView.setProfileId(user.getId()); 
        // Set the Textview's text to the user's name. 
        userNameView.setText(user.getName()); 

        OwnId = user.getId(); 
        OwnUser = user; 

        //ServiceAsyncTask task = new ServiceAsyncTask(); 
        //task.run(); 
       } 
      } 
      if (response.getError() != null) { 
       // Handle errors, will do so later. 
      } 
     } 
    }); 
    request.executeAsync(); 
} 

private void onSessionStateChange(final Session session, SessionState state, Exception exception) { 
    if (session != null && session.isOpened()) { 
     // Get the user's data. 
     makeMeRequest(session); 
    } 
} 

@Override 
public void onResume() { 
    super.onResume(); 
    uiHelper.onResume(); 
} 

@Override 
public void onSaveInstanceState(Bundle bundle) { 
    super.onSaveInstanceState(bundle); 
    uiHelper.onSaveInstanceState(bundle); 
} 

@Override 
public void onPause() { 
    super.onPause(); 
    uiHelper.onPause(); 
} 

@Override 
public void onDestroy() { 
    super.onDestroy(); 
    uiHelper.onDestroy(); 
} 

private class PeopleListElement extends BaseListElement { 

    public PeopleListElement(int requestCode) { 
     super(getActivity().getResources().getDrawable(R.drawable.action_people), 
       getActivity().getResources().getString(R.string.action_people), 
       getActivity().getResources().getString(R.string.action_people_default), 
       requestCode); 
    } 

    @Override 
    protected View.OnClickListener getOnClickListener() { 
     return new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 

       startPickerActivity(PickerActivity.FRIEND_PICKER, getRequestCode()); 
      } 
     }; 
    } 

    @Override 
    protected void populateOGAction(OpenGraphAction action) { 
     // TODO Auto-generated method stub 

    } 
} 

private class ActionListAdapter extends ArrayAdapter<BaseListElement> { 
    private List<BaseListElement> listElements; 

    public ActionListAdapter(Context context, int resourceId, List<BaseListElement> listElements) { 
     super(context, resourceId, listElements); 
     this.listElements = listElements; 
     for (int i = 0; i < listElements.size(); i++) { 
      listElements.get(i).setAdapter(this); 
     } 
    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
     View view = convertView; 
     if (view == null) { 
      LayoutInflater inflater = 
        (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
      view = inflater.inflate(R.layout.listitem, null); 
     } 

     BaseListElement listElement = listElements.get(position); 
     if (listElement != null) { 
      view.setOnClickListener(listElement.getOnClickListener()); 
      ImageView icon = (ImageView) view.findViewById(R.id.icon); 
      TextView text1 = (TextView) view.findViewById(R.id.text1); 
      TextView text2 = (TextView) view.findViewById(R.id.text2); 
      if (icon != null) { 
       icon.setImageDrawable(listElement.getIcon()); 
      } 
      if (text1 != null) { 
       text1.setText(listElement.getText1()); 
      } 
      if (text2 != null) { 
       text2.setText(listElement.getText2()); 
      } 
     } 
     return view; 
    } 

} 

private void startPickerActivity(Uri data, int requestCode) { 
    Intent intent = new Intent(); 
    intent.setData(data); 
    intent.setClass(getActivity(), PickerActivity.class); 
    startActivityForResult(intent, requestCode); 
}  

public void createButton() { 

} 

}

+0

Я смущен. Вы делаете итерацию с целью добавления кнопок, сразу после этого вы вызываете finishActivity(). – cYrixmorten

+0

Финишная активность уже была частью кода примера. Активность заключается только в том, чтобы открыть friendpicker после того, как вы закончите с ним, деятельность закрывается. Это неправильно? –

+0

Ну, вы будете сильно удаляться как от другаPickerFragment, так и от активности, удерживая его, отсюда теряя кнопки. Где именно вы надеетесь заполнить кнопки? Если в действии, в котором хранится опубликованный код, вам нужно удалить вызов для завершенияActivity() – cYrixmorten

ответ

0

Хорошо, это лучшее, что я мог сделать, не зная полностью код.

Насколько я могу судить, тогда ActionListAdapter отвечает за создание списка друзей. Если я прав, то что вам нужно сделать.

  1. Alter Рез/макет/ListItem, добавив вид кнопки с идентификатором, ради примеров пусть это будет btn_friend

    // Somewhere in res/layout/listitem 
        <Button 
         android:id="@+id/btn_friend" 
         android:layout_width="wrap_content" 
         android:layout_height="wrap_content" 
         /> 
    
  2. Alter ActionListAdapter установить текст слушать щелчки

    private class ActionListAdapter extends ArrayAdapter<BaseListElement> { 
        private List<BaseListElement> listElements; 
    
        public ActionListAdapter(Context context, int resourceId, List<BaseListElement> listElements) { 
         super(context, resourceId, listElements); 
         this.listElements = listElements; 
         for (int i = 0; i < listElements.size(); i++) { 
          listElements.get(i).setAdapter(this); 
         } 
        } 
    
        @Override 
        public View getView(int position, View convertView, ViewGroup parent) { 
         View view = convertView; 
         if (view == null) { 
          LayoutInflater inflater = 
            (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
          view = inflater.inflate(R.layout.listitem, null); 
         } 
    
         BaseListElement listElement = listElements.get(position); 
         if (listElement != null) { 
          view.setOnClickListener(listElement.getOnClickListener()); 
          ImageView icon = (ImageView) view.findViewById(R.id.icon); 
          TextView text1 = (TextView) view.findViewById(R.id.text1); 
          TextView text2 = (TextView) view.findViewById(R.id.text2); 
          Button btn = (Button) view.findViewById(R.id.btn_friend); 
          if (icon != null) { 
           icon.setImageDrawable(listElement.getIcon()); 
          } 
          if (text1 != null) { 
           text1.setText(listElement.getText1()); 
          } 
          if (text2 != null) { 
           text2.setText(listElement.getText2()); 
          } 
          if (btn != null) { 
           // I do not know exactly what text1 and text2 is 
           btn.setText(text1 + " waiting for game"); 
           btn.setOnClickListener(new OnClickListener() { 
    
            @Override public void onClick(View v) { 
             Toast.makeText(getActivity(), text1+ " " + text2 + " clicked!", Toast.LENGTH_SHORT).show(); 
            } 
           }); 
          } 
         } 
         return view; 
        } 
    
    } 
    

Надеюсь, я не понял, как работает код.

+0

спасибо, сегодня я попробую ваше решение –

+0

В вашем решении вы не добавляют динамически кнопку, вы просто изменяете существующую, правильно ли, или я чего-то не хватает?Что еще я не понимаю, но, возможно, именно поэтому я не очень хорошо разбираюсь в Java :-), почему мне нужно расширить ActionListAdapter, когда все, что я хочу сделать, это просто добавить кнопку к элементу SelectionFragment View –

+0

Мои мысли что ActionListAdapter расширяет ArrayAdapter, таким образом, это описание того, как должен выглядеть каждый элемент в списке, поэтому я надеюсь, что для каждого из друзей выдается ActionListAdapter.getView (..), который каждый создает свою собственную кнопку, раздувая R .layout.listitem layout. – cYrixmorten