骨子。
【MainActivity.java】
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
MainFragment mFragment = MainFragment.newInstance("渡すデータ。文字以外もOK。");
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, mFragment)
.commitNow();
View view = (View)findViewById(R.id.container);
view.setOnTouchListener((MainFragment)mFragment);
}
}
}
【fragment_main.xml】com.????.MyImageView/????部分はパッケージ名
< androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/mainFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.main.MainFragment">
< com.????.MyImageView
android:id="@+id/main_image"
android:layout_width="match_parent"
android:layout_height="match_parent" />
【MainFragment.java】
public class MainFragment extends Fragment implements View.OnTouchListener {
MyImageView mImageView = null;
private GestureDetectorCompat mDetector = null;
class MyGestureListener extends SimpleOnGestureListener {
@Override
public boolean onDown(MotionEvent event) {
return true;
}
//他、省略。
}
@Override
public boolean onTouch(View v, MotionEvent event) {
return mDetector.onTouchEvent(event);
}
public static MainFragment newInstance(String name) {
MainFragment mainFragment = new MainFragment();// インスタンス生成
Bundle args = new Bundle();// Bundle にパラメータを設定
args.putString("test", name);// 渡す型に合わせてメソッドを変える
mainFragment.setArguments(args);
return mainFragment;
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
}
@Override
public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mDetector = new GestureDetectorCompat(requireContext(), new MyGestureListener());
Bundle args = getArguments();// Bundle にパラメータを取得
if(args != null ){
String name = args.getString("test");
// 受け取った値を処理する
}
mImageView = (MyImageView) view.findViewById(R.id.main_image);
mImageView.setScaleType(ImageView.ScaleType.MATRIX);
try {
AssetManager mAssetManager = getResources().getAssets();
InputStream istream = mAssetManager.open("image/0001.jpg");
Bitmap mBitmap = BitmapFactory.decodeStream(istream);
if (mBitmap != null) mImageView.setImageBitmap(mBitmap);
istream.close();
} catch (Exception e) {
;
}
}
}