2014-12-17 3 views
7

Я работаю над фрагментами ящика NAvigation. Andi скопируйте код действия в фрагменты, чтобы выполнить в фрагменте. Я сделал это, макет виден, но ни одно действие кнопки работы в рамках этого фрагмента деятельности.setOnClickListener (новый OnClickListener() не работает во Фрагменте

Можете ли вы сказать мне, что я сделал неправильно?

FragmentTwo.java

public class FragmentTwo extends Fragment { 

    Button blog,fb,twitter,mail; 
    ImageView dateimg; 
    private boolean snet; 


    public FragmentTwo() 
    { 

    } 

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


     System.out.println("Kaks7"); 
     dateimg = (ImageView) getActivity().findViewById(R.id.img); 
     blog= (Button) getActivity().findViewById(R.id.btnGplus); 
     fb = (Button) getActivity().findViewById(R.id.btnFb); 
     twitter = (Button)getActivity().findViewById(R.id.btnTwitter); 
     mail = (Button)getActivity().findViewById(R.id.btnMail); 
     System.out.println("K17"); 
     new LongOperation().execute(); 


     return view; 
    } 



    private class LongOperation extends AsyncTask<Void, Void, Void> { 



     protected void onPreExecute() { 



     } 


     @Override 
     protected Void doInBackground(Void... params) { 
      // TODO Auto-generated method stub 


      return null; 
     } 


     @Override 
     protected void onPostExecute(Void result) { 

      try{ 

       fb.setOnClickListener(new OnClickListener() 
        { 

          public void onClick(View vb) 
          { 
           try{ 
            System.out.println("7"); 
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("fb://profile/10000003242252")); 
            startActivity(intent); 

            }catch(Exception e){ 

            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://m.facebook.com/facebook"))); 
            } 

           } 

        }); 

       twitter.setOnClickListener(new OnClickListener() 
       { 
         public void onClick(View vc) 
         { 
          try { 

            Intent intent = new Intent(Intent.ACTION_VIEW, 
             Uri.parse("twitter://user?screen_name=dhoom")); 
            startActivity(intent); 

            }catch (Exception e) { 
             startActivity(new Intent(Intent.ACTION_VIEW, 
              Uri.parse("https://mobile.twitter.com/#!/dhoom"))); 
            } 

          } 

       }); 

       blog.setOnClickListener(new OnClickListener() 
       { 
         public void onClick(View va) 
         { System.out.println("7s"); 
          try { 
           System.out.println("5s"); 
           String url = "http://google.com"; 
           Intent i = new Intent(Intent.ACTION_VIEW); 
           i.setData(Uri.parse(url)); 
           startActivity(i); 


          } 

          catch(Exception e){ 
           System.out.println("6s"); 
              startActivity(new Intent(Intent.ACTION_VIEW, 
               Uri.parse("http://www.google.com"))); 
          } 

         } 

       }); 


       mail.setOnClickListener(new OnClickListener() 
       { 
         public void onClick(View va) 
         { 
          try { 
           Intent send = new Intent(Intent.ACTION_SENDTO); 
           String uriText = "mailto:" + Uri.encode("[email protected]") + 
              "?subject=" + Uri.encode("the subject") + 
              "&body=" + Uri.encode("the body of the message"); 
           Uri uri = Uri.parse(uriText); 

           send.setData(uri); 
           startActivity(Intent.createChooser(send, "Send mail...")); 
          } 

          catch(Exception e){ 
           Toast.makeText(getActivity().getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show(); 
          // this.progressDialog.dismiss(); 
          } 
         } 

       }); 

       dateimg.setOnClickListener(new OnClickListener() 
       { 
         public void onClick(View va) 
         { 
          if(snet==false) 
          { 
          soundstart(); 
          snet=true; 
          } 
         } 

       }); 





      } 

      catch(Exception e){ 
       //Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show(); 

      } 
     } 



    } 


    public void soundstart() 
    { 
     // TODO Auto-generated method stub 
     MediaPlayer mplayer =MediaPlayer.create(getActivity(),R.raw.contact_sound); 
     mplayer.start(); 

    } 

} 

активность

<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=".MainActivity" 
    android:background="@drawable/abc"> 

    <RelativeLayout 
    android:layout_width="wrap_content" 
    android:id="@+id/text" 
    android:orientation="vertical" 
    android:gravity="center" 
    android:layout_gravity="center" 
    android:layout_height="wrap_content" > 
     <TextView 
      android:id="@+id/textView1" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:layout_alignParentTop="true" 
      android:gravity="center" 
      android:paddingTop="-30dp" 
      android:text="© iamrajkaran || Raj Karan" 
      android:textAppearance="?android:attr/textAppearanceMedium" 
      android:textColor="#FFFFFF" 
      android:textSize="20sp" 
      android:textStyle="bold" /> 

    </RelativeLayout> 
    <LinearLayout 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentRight="true" 
     android:background="@drawable/linearlayout_bg" 
     android:orientation="vertical" 
     android:layout_marginTop="30dp" 
     android:padding="7dp" > 

     <Button 
      android:id="@+id/btnGplus" 
      style="@style/ButtonText" 
      android:layout_width="fill_parent" 
      android:layout_height="48dp" 
      android:layout_margin="4dp" 
      android:background="@drawable/layers_blog_button_bg" 
      android:padding="10dp" 
      android:text="Know me on my blog" /> 
     <Button 
      android:id="@+id/btnFb" 
      style="@style/ButtonText" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:layout_margin="4dp" 
      android:background="@drawable/layers_fb_button_bg" 
      android:padding="10dp" 
      android:text="Join me on facebook" /> 
     <Button 
      android:id="@+id/btnTwitter" 
      style="@style/ButtonText" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:layout_margin="4dp" 
      android:background="@drawable/layers_twitter_button_bg" 
      android:padding="10dp" 
      android:text="Follow me on twitter" /> 
     <Button 
      android:id="@+id/btnMail" 
      style="@style/ButtonText" 
      android:layout_width="match_parent" 
      android:layout_height="48dp" 
      android:layout_margin="4dp" 
      android:background="@drawable/layers_mail_button_bg" 
      android:padding="10dp" 
      android:text="Mail Your Feedback" /> 


     </LinearLayout> 


    <RelativeLayout 
    android:layout_width="fill_parent" 
    android:id="@+id/texwt" 
    android:orientation="vertical" 
    android:gravity="bottom" 
    android:layout_gravity="center" 
    android:layout_marginTop="240dp" 
    android:layout_height="wrap_content" > 
     <ImageView 
      android:id="@+id/img" 
      android:layout_width="180dp" 
      android:layout_height="180dp" 
      android:layout_alignParentBottom="true" 
      android:layout_centerHorizontal="true" 
      android:gravity="center" 
      android:paddingLeft="30dp" 
       android:paddingRight="0dp" 
      android:src="@drawable/ic_form" /> 

    </RelativeLayout> 
    <TextView 
     android:id="@+id/textView2" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_alignParentBottom="true" 
     android:gravity="center" 
     android:layout_marginTop="40dp" 
     android:text="Touch Me" 
     android:textAppearance="?android:attr/textAppearanceMedium" 
     android:textColor="#FFFFFF" 
     android:textSize="22sp" 
     android:textStyle="bold" /> 

</RelativeLayout>** 
+0

Сбой или ошибки –

+0

Зачем устанавливать onClickListeners в AsyncTask? Вы не должны этого делать. – Kelevandos

+0

Нет никаких сбоев вообще. Он показывает мне макет, но oclick не работает – Creator

ответ

5

инициализировать ур виджетов следующим образом.

dateimg = (ImageView) view.findViewById(R.id.img); 
blog= (Button) view.findViewById(R.id.btnGplus); 
fb = (Button) view.findViewById(R.id.btnFb); 
twitter = (Button) view.findViewById(R.id.btnTwitter); 
mail = (Button) view.findViewById(R.id.btnMail); 
+0

спасибо, что он работал – Creator

+0

приветствуется приятель .. –

0

Изменить все View.OnClickListener() к View.OnclickListener():

fb.setOnClickListener(new View.OnclickListener() { 
    @Override 
    public void onClick(View v) { 
    } 
}); 
6

использовать представление вместо использования getactivity(), ваш получить вид с раздувать точки зрения, так что используйте view

dateimg = (ImageView) view.findViewById(R.id.img); 

вместо от

dateimg = (ImageView) getActivity().findViewById(R.id.img); 

изменение аналогично для всех видов виджетов.

2

изменение:

dateimg = (ImageView) getActivity().findViewById(R.id.img); 
blog= (Button) getActivity().findViewById(R.id.btnGplus); 
fb = (Button) getActivity().findViewById(R.id.btnFb); 
twitter = (Button)getActivity().findViewById(R.id.btnTwitter); 
mail = (Button)getActivity().findViewById(R.id.btnMail); 

в

dateimg = (ImageView) view.findViewById(R.id.img); 
blog= (Button) view.findViewById(R.id.btnGplus); 
fb = (Button) view.findViewById(R.id.btnFb); 
twitter = (Button)view.findViewById(R.id.btnTwitter); 
mail = (Button)view.findViewById(R.id.btnMail); 

текущий вид является view, и вы должны инициализировать ваш взгляд, как и выше, или вы можете переопределить onViewCreate() и использовать view на что

0

вместо

dateimg = (ImageView) getActivity().findViewById(R.id.img); 
blog= (Button) getActivity().findViewById(R.id.btnGplus); 
fb = (Button) getActivity().findViewById(R.id.btnFb); 
twitter = (Button)getActivity().findViewById(R.id.btnTwitter); 
mail = (Button)getActivity().findViewById(R.id.btnMail); 

вам необходимо инициализировать

mail = (Button)view.findViewById(R.id.btnMail); 

как с помощью getActivity(). FindViewById (...) у вызываем метод вашей деятельности в то время как вам нужно CaAl то же самое для frafment.

Смежные вопросы