【问题标题】:How can I run the viewpager program with using Action Bar? Because after I add the action bar, program stops如何使用操作栏运行 viewpager 程序?因为在我添加操作栏后,程序停止
【发布时间】:2016-04-29 17:50:44
【问题描述】:

我正在尝试结合视图寻呼机做两个不同的片段。但是,当我运行它时程序会停止。我找不到问题。你能帮助我吗?谢谢。

//StartingTestActivity.java

import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import java.util.List;
import java.util.Vector;


public class StartingTestActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
    private Spinner spinner;
    ArrayAdapter<CharSequence> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_startingtest);

        spinner = (Spinner)findViewById(R.id.spinner);
        adapter = ArrayAdapter.createFromResource(this,R.array.simple_spinner_dropdown_item,R.layout.spinner_item);
        adapter.setDropDownViewResource(R.layout.spinner_dropdown_item);

        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(this);

        Typeface ubuntu_MI = Typeface.createFromAsset(getAssets(),"Ubuntu-MI.ttf");
        Typeface ubuntu_L = Typeface.createFromAsset(getAssets(),"Ubuntu-L.ttf");
        Typeface ubuntu_R = Typeface.createFromAsset(getAssets(),"Ubuntu-R.ttf");

        TextView info = (TextView) findViewById(R.id.textView6);
        TextView question = (TextView) findViewById(R.id.textView7);

        info.setTypeface(ubuntu_R);
        question.setTypeface(ubuntu_R);


        // Get the ActionBar
        android.support.v7.app.ActionBar ab = getSupportActionBar();


        // Create a TextView programmatically.
        TextView tv = new TextView(getApplicationContext());

        // Create a LayoutParams for TextView
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.MATCH_PARENT, // Width of TextView
                RelativeLayout.LayoutParams.WRAP_CONTENT); // Height of TextView

        // Apply the layout parameters to TextView widget
        tv.setLayoutParams(lp);

        // Set text to display in TextView
        // This will set the ActionBar title text
        tv.setText("Anasayfa");

        // Set the text color of TextView
        // This will change the ActionBar title text color
        tv.setTextColor(Color.parseColor("#FFF5EE"));

        // Center align the ActionBar title
        tv.setGravity(Gravity.CENTER_HORIZONTAL);

        // Set the serif font for TextView text
        // This will change ActionBar title text font
        tv.setTypeface(ubuntu_MI);

        // Underline the ActionBar title text
        // tv.setPaintFlags(tv.getPaintFlags()| Paint.UNDERLINE_TEXT_FLAG);

        // Set the ActionBar title font size
        tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP,24);

        // Display a shadow around ActionBar title text
        //tv.setShadowLayer(
        //      1.f, // radius
        //    2.0f, // dx
        //  2.0f, // dy
        //  Color.parseColor("#FF8C00") // shadow color
        //);

        // Set the ActionBar display option
        ab.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);

        // Finally, set the newly created TextView as ActionBar custom view
        ab.setCustomView(tv);
    }


    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.activity_startingtest,container,false);
        return rootView;
    }
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

        switch (position) {
            case 0:
                // Whatever you want to happen when the first item gets selected
                break;
            case 1:
                // Whatever you want to happen when the second item gets selected
                break;
            case 2:
                // Whatever you want to happen when the thrid item gets selected
                break;

        }

    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
}

//ProfileActivity.java

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


public class ProfileActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);

        Typeface ubuntu_MI = Typeface.createFromAsset(getAssets(),"Ubuntu-MI.ttf");
        Typeface ubuntu_R = Typeface.createFromAsset(getAssets(),"Ubuntu-R.ttf");

        // Get the ActionBar
        android.support.v7.app.ActionBar ab = getSupportActionBar();


        // Create a TextView programmatically.
        TextView tv = new TextView(getApplicationContext());

        // Create a LayoutParams for TextView
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.MATCH_PARENT, // Width of TextView
                RelativeLayout.LayoutParams.WRAP_CONTENT); // Height of TextView

        // Apply the layout parameters to TextView widget
        tv.setLayoutParams(lp);

        // Set text to display in TextView
        // This will set the ActionBar title text
        tv.setText("Profil");

        // Set the text color of TextView
        // This will change the ActionBar title text color
        tv.setTextColor(Color.parseColor("#FFF5EE"));

        // Center align the ActionBar title
        tv.setGravity(Gravity.CENTER);

        // Set the serif font for TextView text
        // This will change ActionBar title text font
        tv.setTypeface(ubuntu_MI);

        // Underline the ActionBar title text
        // tv.setPaintFlags(tv.getPaintFlags()| Paint.UNDERLINE_TEXT_FLAG);

        // Set the ActionBar title font size
        tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP,24);

        // Display a shadow around ActionBar title text
        //tv.setShadowLayer(
        //      1.f, // radius
        //    2.0f, // dx
        //  2.0f, // dy
        //  Color.parseColor("#FF8C00") // shadow color
        //);

        // Set the ActionBar display option
        ab.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);

        // Finally, set the newly created TextView as ActionBar custom view
        ab.setCustomView(tv);
    }
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.activity_profile,container,false);
        return rootView;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
    //Action Bar' daki settings kısmına basıldığında ne yapacağını söylüyoruz.
        if(item.getItemId() == R.id.settings){
            Toast.makeText(this, "Ayarlara basıldı", Toast.LENGTH_SHORT).show();
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_profile_activity, menu);
        return true;
    }
}

// PagerAdapter1.java

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import java.util.List;

public class PagerAdapter1 extends FragmentPagerAdapter {

    private List<Fragment> fragments;

    public PagerAdapter1(FragmentManager fm, List<Fragment> fragments) {
        super(fm);
        this.fragments = fragments;
    }

    @Override
    public Fragment getItem(int position) {
        return this.fragments.get(position);
    }

    @Override
    public int getCount() {
        return this.fragments.size();
    }
}

//CombineFragmentActivity.java

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;

import java.util.List;
import java.util.Vector;

/**
 * Created by KHas on 29.04.2016.
 */
public class CombineFragmentActivity extends AppCompatActivity {
    private PagerAdapter mPagerAdapter;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initialisePaging();

    }
    private void initialisePaging() {

        List<Fragment> fragments = new Vector<Fragment>();
        fragments.add(Fragment.instantiate(this,StartingTestActivity.class.getName()));
        fragments.add(Fragment.instantiate(this,ProfileActivity.class.getName()));
        mPagerAdapter = new PagerAdapter1(this.getSupportFragmentManager(),fragments);

        ViewPager pager = (ViewPager)findViewById(R.id.viewpager);
        pager.setAdapter(mPagerAdapter);
    }
}

错误:

【问题讨论】:

  • 你能添加你的错误堆栈吗??

标签: android android-fragments android-viewpager fragment android-fragmentactivity


【解决方案1】:

ViewPager 适配器期待片段,而 StartingTestActivity 是一个应该扩展片段而不是 AppCompatActivity 的活动

public class CombineActivity extends AppCompatActivity {
    ....
    private ViewPager viewPager;

    public onCreate(Bundle savedInstance) {
        // Prefer using toolbar from support library as actionBar
        Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        YourAdapter adapter = new YourAdapter(getSupportFragmentManager());
       .....
       // Add your
       adapter.addFragment(new FragmentExemple.nexInstance());
     ......


    }
}

现在你如何实现 Fragment 类

public class FragmentExample extends Fragment {
       public static FragmentExemple newInstance() {
          return new FragmentExample();  
      }
     // Now fragment is almost like an activity if have it own life cycle
  @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
       // just example
    Bundle args = getArguments();

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
 // this is the equivalent of setContentView in an activity you specify witch layout to use for this fragment
 View rootView = inflater.inflate(R.layout.fragment_previous, container,  false);
    return rootView
 }
}

我忘记了你是否有一个特殊的操作栏项目,根据女巫片段显示是否处于活动状态

// use auto completion of android studio to correct this method call :)
    public void onViewCreated(View view) {
             // this will inform the activity that this fragment contribute the actionbar items
           setHasOptionsMenu(true)
    }

并将 OnCreateOptionMenu 和 onOptionMenuItemSelected 方法添加到您的片段(不要忘记使用 AndroidStudio 自动完成来调用这些方法,我总是忘记那里的实现语法;))

【讨论】:

  • 但是,我必须使用 AppCompatActivity 在我的项目中添加操作栏。我该如何解决这个问题?
  • 我在等你的例子。非常感谢。
  • 我在示例中使用了工具栏,但它不是必需的,您可以像在代码中一样继续使用操作栏
  • Okey,但它现在给出错误。我不知道如何在 CombineActivity 中实现 AppCompatActivity 并从 Fragments 访问。
【解决方案2】:

有你的 StartingTestActivity 类作为片段

public class StartingTestActivity extends Fragment implements AdapterView.OnItemSelectedListener {
private Spinner spinner;
ArrayAdapter<CharSequence> adapter;



public StartingTestActivity() {
    // Required empty public constructor
}


public static StartingTestActivity newInstance() {
    StartingTestActivity fragment = new StartingTestActivity();
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.R.layout.activity_startingtest, container, false);
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    spinner = (Spinner)view.findViewById(R.id.spinner);
    adapter = ArrayAdapter.createFromResource(getActivity(),R.array.simple_spinner_dropdown_item,R.layout.spinner_item);
    adapter.setDropDownViewResource(R.layout.spinner_dropdown_item);

    spinner.setAdapter(adapter);
    spinner.setOnItemSelectedListener(this);

    Typeface ubuntu_MI = Typeface.createFromAsset(getActivity().getAssets(),"Ubuntu-MI.ttf");
    Typeface ubuntu_L = Typeface.createFromAsset(getActivity().getAssets(),"Ubuntu-L.ttf");
    Typeface ubuntu_R = Typeface.createFromAsset(getActivity().getAssets(),"Ubuntu-R.ttf");

    TextView info = (TextView) view.findViewById(R.id.textView6);
    TextView question = (TextView) view.findViewById(R.id.textView7);

    info.setTypeface(ubuntu_R);
    question.setTypeface(ubuntu_R);


    // Get the ActionBar
    android.support.v7.app.ActionBar ab = ((AppCompatActivity)getActivity()).getSupportActionBar();


    // Create a TextView programmatically.
    TextView tv = new TextView(getActivity());

    // Create a LayoutParams for TextView
    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT, // Width of TextView
            RelativeLayout.LayoutParams.WRAP_CONTENT); // Height of TextView

    // Apply the layout parameters to TextView widget
    tv.setLayoutParams(lp);

    // Set text to display in TextView
    // This will set the ActionBar title text
    tv.setText("Anasayfa");

    // Set the text color of TextView
    // This will change the ActionBar title text color
    tv.setTextColor(Color.parseColor("#FFF5EE"));

    // Center align the ActionBar title
    tv.setGravity(Gravity.CENTER_HORIZONTAL);

    // Set the serif font for TextView text
    // This will change ActionBar title text font
    tv.setTypeface(ubuntu_MI);

    // Underline the ActionBar title text
    // tv.setPaintFlags(tv.getPaintFlags()| Paint.UNDERLINE_TEXT_FLAG);

    // Set the ActionBar title font size
    tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP,24);

    // Display a shadow around ActionBar title text
    //tv.setShadowLayer(
    //      1.f, // radius
    //    2.0f, // dx
    //  2.0f, // dy
    //  Color.parseColor("#FF8C00") // shadow color
    //);

    // Set the ActionBar display option
    ab.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);

    // Finally, set the newly created TextView as ActionBar custom view
    ab.setCustomView(tv);
}

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    switch (position) {
        case 0:
            // Whatever you want to happen when the first item gets selected
            break;
        case 1:
            // Whatever you want to happen when the second item gets selected
            break;
        case 2:
            // Whatever you want to happen when the thrid item gets selected
            break;

    }
}

@Override
public void onNothingSelected(AdapterView<?> parent) {

}

}

【讨论】:

  • 我添加了我的 CombineFragmentActivity。我也在 CombineFragment Activity 和 ProfileActivity 中苦苦挣扎。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多