操作栏按钮不起作用

时间:2015-10-13 09:05:47

标签: android android-actionbar

我是Android开发的新手。我创建了一个应用,其中MainActivity包含Gridview图片,ActivityTwo是所选图片的fullscreen视图我正在尝试在操作栏上添加一个后退按钮。图标是可见的,但它不可点击。我还尝试添加其他菜单项,这些项目也可见,但触摸它们时没有任何反应。我也尝试将onClickListener添加到一些帖子中建议的菜单项,但它似乎不起作用。

下面是ActivityTwo代码。

public class ActivityTwo extends ActionBarActivity implements OnClickListener {

    protected int currentPosition;
    Button share,back;
    ImageView imageView;
    ViewPager viewPager;
    private Toolbar toolbar;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_two);
        toolbar= (Toolbar)findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);      
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        share = (Button)findViewById(R.id.button1);
        share.setOnClickListener(this);
        back=(Button)findViewById(R.id.button2);
        back.setOnClickListener(this);




        // get intent data
        Intent i = getIntent();

        // Selected image id
        final int position = i.getExtras().getInt("position");

        viewPager = (ViewPager) findViewById(R.id.view_pager);
        ImagePagerAdapter adapter = new ImagePagerAdapter();
        viewPager.setAdapter(adapter);
        viewPager.setCurrentItem(position);
        viewPager.setOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {
                // TODO Auto-generated method stub

                currentPosition = arg0;

            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
                // TODO Auto-generated method stub

            }

        });





    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    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_settings) {
            return true;
        }
        if
        (id==R.id.home)
        {
            NavUtils.navigateUpFromSameTask(this);
        }
        return super.onOptionsItemSelected(item);
    }


    public class ImagePagerAdapter extends PagerAdapter {
        Integer[] icons = MainActivity.mThumbIds;

        @Override
        public int getCount() {
            return icons.length;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == ((ImageView) object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            Context context = ActivityTwo.this;
            imageView = new ImageView(context);
            //ImageView imageView = (ImageView)findViewById(R.id.imageView);
            // int padding = context.getResources().getDimensionPixelSize(
            // R.dimen.padding_large);
            imageView.setPadding(5, 5, 5, 5);
            imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
            imageView.setImageResource(icons[position]);
            imageView.setTag(position);
            ((ViewPager) container).addView(imageView, 0);
            return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            ((ViewPager) container).removeView((ImageView) object);
        }
    }
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if(v==share){
        ImageView Imgv = (ImageView)viewPager.findViewWithTag(viewPager.getCurrentItem());
        Drawable mDrawable = Imgv.getDrawable();
        Bitmap mBitmap = ((BitmapDrawable)mDrawable).getBitmap();

        String path = Images.Media.insertImage(getContentResolver(), 
            mBitmap, "Image Description", null);

        Uri uri = Uri.parse(path);




            Intent shareIntent = new Intent();
            shareIntent.setAction(Intent.ACTION_SEND);
            shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
            shareIntent.setType("image/*");

            startActivity(Intent.createChooser(shareIntent, "Share Image"));    }
        if(v==back)
        {
            finish();
        }

    } 
}

2 个答案:

答案 0 :(得分:0)

尝试将此代码添加到工具栏中以便导航

toolbar.setNavigationOnClickListener(new View.OnClickListener() {
    @Override
        public void onClick(View v) {
            onBackPressed();
    }
});

对于工具栏中的其他项目

@Override
 public boolean onOptionsItemSelected(MenuItem item) {
     switch (item.getItemId()) {
         case R.id.action_settings:
             Toast.makeText(context, "setting", Toast.LENGTH_SHORT).show();
             break;
         case R.id.action_share:
             Toast.makeText(context, "share", Toast.LENGTH_SHORT).show();
             break;

     }
 }

希望这个帮助

答案 1 :(得分:0)

要使您的应用图标“可点击”作为后退按钮,您的活动必须遵循父子层次结构。

示例:

  • 活动A是您的主要活动。
  • 按某些内容(比如ListView项目或GridView项目)将启动活动B.

通过这种方式,活动A被称为活动B的父活动。

您可以在清单中以XML格式定义此内容,如下所示:

<div class="container" ng-controller="dataController">
...
    <select ng-model="selectedOption" ng-change="showData()">
      <option ng-repeat="entry in transactions" ng-value="entry.serial">{{ entry.serial }}</option>
    </select>
  </div>
  <div class="col-md-9">
    <table class="table table-hover table-striped table-condensed">
    ...
    <tbody>
      <tr ng-repeat="entry in dataHistory">
        <td>{{ entry.id }}</td>
        <td>{{ entry.timestamp | date:"yyyy MMM dd 'at' h:mm:ssa" }}</td>
        <td>{{ entry.amount }}</td>
      </tr>
    </tbody>
  </table>
</div>

这将使应用程序图标显示在其左侧的后退箭头(&lt;)。

然后我们必须处理click事件。

我们在Activity B中的 onOptionsItemSelected 方法中这样做:

...
.controller('dataController', ['$scope', '$firebaseArray', function($scope, $firebaseArray) {
    ...    
    $scope.showData = function() {
      $scope.dataHistory = [];
      transfersRef.orderByChild('serial').equalTo($scope.selectedOption).on('child_added', function(snap) {
        transactionsRef.orderByKey().equalTo(snap.val().transactionID).on('child_added', function(data) {
          var entry = {};
          entry = data.val();
          entry.id = data.key();
          usersRef.child(entry.fromUserId).child('name').once('value', function(nameSnap) { entry.fromUsername = nameSnap.val(); });
          usersRef.child(entry.toUserId).child('name').once('value', function(nameSnap) { entry.toUsername = nameSnap.val(); });
          console.log('entry: \n' + entry);
          $scope.dataHistory.push(entry);
        });
      });
    };
  }])
...

android.R.id.home 是我们正在收听的点击事件的ID。

有时您可能希望模拟后退按钮而不是以意图启动活动A。你可以这样做:

<activity
    android:name="com.example.android.ActivityA"
    android:label="@string/title_activity_a" />

<activity
    android:name="com.example.android.ActivityB"
    android:label="@string/title_activity_b"
    android:parentActivityName="com.example.android.ActivityA">
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value="com.example.android.ActivityA" />
</activity>