我正在尝试学习 android studio,我制作了一个应用程序,在该应用程序中有一个屏幕显示带有按钮的图像,可以移动到上一个/下一个图像。现在显示了图像,但按钮不起作用,我的图像也没有改变。
以下是我的java文件的代码
package com.example.myapplication;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class PhotoGalleryFragment extends Fragment {
private int[] imageIds = { R.drawable.image1, R.drawable.image2, R.drawable.image3, R.drawable.image4, R.drawable.image5 };
private int currentIndex = 0;
private ImageView imageView;
private Button previousButton;
private Button nextButton;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_photo_gallery, container, false);
imageView = view.findViewById(R.id.imageView);
previousButton = view.findViewById(R.id.previousButton);
nextButton = view.findViewById(R.id.nextButton);
imageView.setImageResource(imageIds[currentIndex]);
previousButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
currentIndex--;
if (currentIndex < 0) {
currentIndex = imageIds.length - 1;
}
imageView.setImageResource(imageIds[currentIndex]);
}
});
nextButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
currentIndex++;
if (currentIndex >= imageIds.length) {
currentIndex = 0;
}
imageView.setImageResource(imageIds[currentIndex]);
}
});
return view;
}
}
以下是该文件的 xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:scaleType="fitCenter" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<Button
android:id="@+id/previousButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="false"
android:text="Previous" />
<Button
android:id="@+id/nextButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next" />
</LinearLayout>
</LinearLayout>
以下是我得到的屏幕,点击按钮时图像没有改变
嗨你应该删除
android:clickable="false"
或设置android:clickable="true"
<Button
android:id="@+id/previousButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="false"
android:text="Previous" />
在您的 Previous 按钮属性中,您设置了 android:clickable="false"。因此按钮处于非活动状态。将其设置为 true,您就可以开始了。 希望这能解决你的问题。